#!/usr/bin/env perl

BEGIN {
	push @INC,".." if -f "../pv3.pm";
	push @INC,$ENV{CODEMGR_LIBS} if exists($ENV{CODEMGR_LIBS});
}

use pv3;
use Data::Dumper;
use Getopt::Long;
use strict;
use Config;

$::ARG_pv=undef;
$::ARG_c=0;
$::ARG_target=undef;
$::ARG_version=undef;

sub usage {
	print "
Usage: pv3_get [-p DIR] [-v V] [-c|-t name] file ...

The pv3_get allows a specified version to be retrieved
read-only from the files given under version control.
Use this to retrieve copies to view/package, not to edit - 
that is done using pv_co.

At present it supports the following command line arguments:

-p  By default the file in question containing the versions is
    thought to exist in the current directory. Use this option
    to reference the version file kept elsewhere.
-v  Indicate the version to retrieve. If not specified it defaults
    to the latest version.
-c  Show the necessary contents to the screen. When this option is
    used rather than writing to a file the contents in question 
    are shown on the standard output - no disk files are written.
-t  Target filename format - use '%' to represent the existing 
    filename. So a common usage might be '-t %.2'.

Written by Simon Edwards, (C) 2006-2010 www.advantsys.co.uk
";
	exit 1;
}

if(!GetOptions(
	"target=s"	=> \$::ARG_target,
	"pv=s"		=> \$::ARG_pv,
	"version=s"	=> \$::ARG_version,
	"c"		=> \$::ARG_c,
	)) {
	usage;
}

if($::ARG_c && defined($::ARG_target)) {
	usage;
}

my %args=();
if(defined($::ARG_version)) {
	$args{VERSION}=$::ARG_version;
}
if($::ARG_c || defined($::ARG_target)) {
	$args{MEMCOPY}=1;
}

@::CHECK_OUT_LIST=();

if($Config{osname} =~ /mswin/i) {
	my @F=();
	for my $cpat (@ARGV) {
		push @F,glob($cpat);
	}
	@ARGV=@F;
}

for my $cfile (@ARGV) {
	next if -d $cfile;
	next if $cfile =~ /,pv3$/;
	# We do not check for local only files, since it might
	# have been deleted from the local directory....
	push @::CHECK_OUT_LIST,$cfile;

}
{
	$args{PVFILE}=$::ARG_pv if defined($::ARG_pv);
	my $res=pv3::get(FILE => [@::CHECK_OUT_LIST],%args);
	my $errors=0; my $oks=0;
	my $memcopy=0;
	if($::ARG_c || defined($::ARG_target)) {
		$memcopy=1;
	}
	for my $c (@$res) {
		if($c->[0]==0) {
			$errors++;
			if(!defined($c->[2]) || !length($c->[2])) {
				print "ERROR: $c->[1]\n";
			} else {
				print "ERROR: $c->[2] - $c->[1]\n";
			}
		} else {
			if($memcopy) {
				my $d=$c->[4];
				if($::ARG_c) {
					print $$d;
				} else {
					my $fd;
					my $f2=$c->[3];
					my $x=$::ARG_target;
					$x =~ s/\%/$f2/g;
					if(open($fd,">$x")) {
						print $fd $$d;
						close($fd);
						print "GET  : $c->[3]=>$x - $c->[2] [",$c->[1],"]\n";
						$oks++;
					} else {
						print "ERROR: Unable to write to $x: $!\n";
					}
				}
			} else {
				$oks++;
				print "GET  : $c->[3] - $c->[2] [",$c->[1],"]\n";
			}
		}
	}
}
exit(0);
